﻿import QtQuick 2.0

Loader {
    id: loader;
    property var defObj: null;
    property int id: -1;
    property string color: "";
    property bool isCur: false;
    signal request(string jsStr);
    
    asynchronous: true;
    Component.onCompleted: Qt.callLater(init);
    
    onLoaded: {
        if( !isCur )
            return;
        
        //当前角色
        item.createRanName();
        request(getRegisterPackage());
        Qt.callLater(initRoleRefreshTimer);
    }
    
    function init(){
        var arg = {"id": id}
        if( !isCur )
        {
            arg.name = defObj.name;
            arg.color = defObj.color;
        }
        arg.isCur = isCur;
        
        setSource("qrc:/MRoleItem_def.qml",arg);
    }
    
    /*!每隔30毫秒提交一次当前角色状态到服务器
     */
    function initRoleRefreshTimer(){
        var tCpt = Qt.createQmlObject('import QtQuick 2.0; Timer{repeat: true; interval: 25;}',loader,"timer");
        tCpt.triggered.connect(
                    function(){
                        request(getStatePackage());
                    });
        tCpt.start();
    }
    
    /*!刷新设置其他角色的状态
     */
    function refreshSta(jsObj){
        if( isCur || !item )
            return;
        item.x = jsObj.x;
        item.y = jsObj.y;
        item.blood = jsObj.blood;
    }
    
    function setPosition(x,y){
        if( item )
            item.setPosition(x,y);
    }
    
    function getRegisterPackage(){
        var obj = {
            "cmd": "role_register",
            "id": item.id,
            "name": item.name,
            "color": item.color+""
        }
        return JSON.stringify(obj);
    }
    
    function getStatePackage(){
        if( !item )
            return "";
        
        return JSON.stringify(stateObj());
    }
    
    function stateObj(){
        var obj = {
            "cmd": "role_refresh",
            "id": item.id,
            "x": item.x,
            "y": item.y,
            "blood": item.blood
        }
        return obj;
    }
}
